package com.xuhuan.gulimall.product.exception;

import com.xuhuan.common.exception.BizCodeEnum;
import com.xuhuan.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author huan.xu
 * @Date 2022/5/13 23:02
 * @Description 统一异常处理
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.xuhuan.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    /**
     * 数据校验错误异常统一处理
     *
     * @param e
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMesMap = new HashMap(16);
        bindingResult.getFieldErrors().stream()
                .forEach(fieldError -> {
                    errorMesMap.put(fieldError.getField(), fieldError.getDefaultMessage());
                });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data", errorMesMap);
    }

    /**
     * 其他异常处理
     *
     * @param e
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable e) {
        log.error("{},错误信息:{}", BizCodeEnum.UNKNOW_EXCEPTION.getMsg(), ExceptionUtils.getFullStackTrace(e));
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
